package com.feather.common.data.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.feather.common.data.DataColumn;
import com.feather.common.data.DataColumnCollection;
import com.feather.common.data.DataRow;
import com.feather.common.data.DataRowCollection;

/**
 * @author flogyin
 */
public class SimpleDataRowCollection implements DataRowCollection, java.io.Serializable {
	private static final long		serialVersionUID	= 1L;

	protected ArrayList<DataRow>	collection			= new ArrayList<DataRow>();

	@Override
	public int getCount() {
		return this.collection.size();
	}

	@Override
	public DataRow get(int rowIndex) {
		return this.collection.get(rowIndex);
	}

	@Override
	public DataColumnCollection getColumns(int columnIndex) {
		SimpleDataColumnCollection collection = new SimpleDataColumnCollection();
		int count = getCount();
		for (int i = 0; i < count; i++) {
			DataRow dataRow = get(i);
			DataColumn dataColumn = dataRow.get(columnIndex);
			collection.add(dataColumn);
		}
		return collection;
	}

	@Override
	public DataColumnCollection getColumns(String columnName) {
		SimpleDataColumnCollection collection = new SimpleDataColumnCollection();
		int count = getCount();
		for (int i = 0; i < count; i++) {
			DataRow dataRow = get(i);
			DataColumn dataColumn = dataRow.get(columnName);
			collection.add(dataColumn);
		}
		return collection;
	}

	@Override
	public void add(DataRow row) {
		if (row != null)
			this.collection.add(row);
	}

	@Override
	public void insertAt(DataRow row, int pos) {
		if (row != null)
			this.collection.add(pos, row);
	}

	@Override
	public int indexOf(DataRow row) {
		if (row != null) {
			int size = this.collection.size();
			for (int i = 0; i < size; i++) {
				DataRow temp = this.collection.get(i);
				if (temp == row)
					return i;
			}
		}
		return -1;
	}

	@Override
	public void remove(DataRow row) {
		int rowIndex = indexOf(row);
		if (rowIndex > -1)
			this.collection.remove(rowIndex);
	}

	@Override
	public void removeAt(int rowIndex) {
		this.collection.remove(rowIndex);
	}

	@Override
	public void clear() {
		this.collection.clear();
	}

	@Override
	public List<Map<String, ?>> toMap() {
		ArrayList<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
		int rowsCount = getCount();
		for (int r = 0; r < rowsCount; r++) {
			list.add(get(r).toMap());
		}
		return list;
	}

	@Override
	public String toJson() {
		return JSON.toJSONString(toMap());
	}
}
